package com.likai.blog.controller;

import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.likai.blog.pojo.Blogger;
import com.likai.blog.service.IBloggerService;
import com.likai.blog.utils.AnswerJson;
import com.likai.blog.utils.CryptographyUtil;

/**
 * 博主Controller控制层
 * @author likai
 * @since 2018-04-30
 */
@Controller
@RequestMapping("/blogger")
public class BloggerController {

	@Autowired
	@Qualifier("bloggerService")
	private IBloggerService bloggerService ;
	
	@ResponseBody
	@RequestMapping(value="/login",method=RequestMethod.POST)
	public ResponseEntity<AnswerJson> login(
			Blogger po,
			HttpServletRequest request
			) {
		AnswerJson json = new AnswerJson() ;
		Subject subject = SecurityUtils.getSubject() ;
		UsernamePasswordToken usernamePasswordToken = 
				new UsernamePasswordToken(po.getUserName(),CryptographyUtil.md5(po.getPassword(), po.getUserName())) ;
		try {
			subject.login(usernamePasswordToken);
			request.getSession().setAttribute("currentUser", po);
			json.setData("登录成功!");
			return new ResponseEntity<AnswerJson>(json,HttpStatus.OK) ;
		} catch(Exception e) {
			e.printStackTrace();
			json.setData("登录失败，用户名密码错误!");
			json.setError("1");
			return new ResponseEntity<AnswerJson>(json,HttpStatus.OK) ;
		}
	
	}
	
	/**
	 * 关于博主
	 * @return
	 */
	@RequestMapping(value="/aboutMe")
	public ModelAndView about() {
		ModelAndView mv = new ModelAndView() ;
		
		mv.addObject("mainPage", "/foreground/blogger/info.jsp") ;
		
		mv.addObject("pageTitle", "关于博主") ;
		
		mv.setViewName("mainTemp");
		return mv ;
	}
	
	
}
